import { HYEventStore } from "hy-event-store"
import { getSongDetail, getSongLyric } from "../server/api_player"
import { parseLyric } from "../utils/parse-lyric"

// const audioContext = wx.createInnerAudioContext()
const audioContext = wx.getBackgroundAudioManager()
const playerStore = new HYEventStore({ 
    state: {
      id: 0,
      isStoping: false,
      currentSong: {},
      durationTime: 0,
      lyricInfos: [],

      currentTime: 0,
      currentLyricIndex: 0,
      currentLyricText: "",

      isPlaying: false,   // 暂停和播状态

      playModeIndex: 0, //0：循坏 1：单曲 2：随机
      palyListSongs: [],
      playListIndex: 0,
    },
    actions : {
      playMusicWithSongIdAction(ctx, { id, isRefresh = false }) {
         if (ctx.id == id && !isRefresh) {
        this.dispatch("changeMusicPlayStatusAction", true)
        return
      }
       ctx.id = id
        // 0.修改播放的状态
        ctx.isPlaying = true
        ctx.currentSong = {},
        ctx.durationTime = 0,
        ctx.lyricInfos = [],
  
        ctx.currentTime = 0,
        ctx.currentLyricIndex = 0,
        ctx.currentLyricText = "",

       // 请求数据
       // 请去歌词详情
       getSongDetail(id).then(res => {
        ctx.currentSong = res.songs[0]
        ctx.durationTime = res.songs[0].dt
        audioContext.title = res.songs[0].name
       })

       // 请求歌词数据
     getSongLyric(id).then(res => {
        const lyricString = res.lrc.lyric
        const lyrice = parseLyric(lyricString)
        ctx.lyricInfos = lyrice
       }) 

       // 2.播放对应id的歌曲
       audioContext.stop()
       audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
       audioContext.title = id
       audioContext.autoplay = true

       // 3监听audioContext一些事件
       this.dispatch("setupAudioContextListenerAction")
      },

      setupAudioContextListenerAction(ctx) {
       // 监听歌词可以播放
       audioContext.onCanplay(() => {
        audioContext.play()
    })
    // 监听时间改变

    // 监听当前播放器播放的时间
    audioContext.onTimeUpdate(() => {
        // 获取当前时间
        const currentTime = audioContext.currentTime * 1000

            ctx.currentTime = currentTime
            // 3.根据当前时间去查找播放的歌词
            if(!ctx.lyricInfos.length) return
        for (let i = 0; i < ctx.lyricInfos.length; i++) {
            const lyricInfos  = ctx.lyricInfos[i]
            if (currentTime < lyricInfos.time) {
                // 设置当前歌词和索引
                const currentIndex = i -1
                if(ctx.currentLyricIndex !== currentIndex) {
                    const currentLyricInfo = ctx.lyricInfos[currentIndex]
                    ctx.currentLyricIndex = currentIndex
                    if(currentLyricInfo.text !== undefined) {
                      ctx.currentLyricText =  currentLyricInfo.text
                    }
                }
                    break
            }
               
            }
           
        })
        //3.监听歌曲播放完进行下一首
        audioContext.onEnded(() =>  {
          this.dispatch("changeNewMusicAction")
        })

        // 4.监听音听暂停/播放
        audioContext.onPlay(() => {
          ctx.isPlaying = true
        })
        audioContext.onPause(() => {
          ctx.isPlaying = false
        })
        audioContext.onStop(() => {
          ctx.isPlaying = false
          ctx.isStoping = true
        })
      },

      changeMusicPlayStatusAction(ctx, isplaying = true) {
        ctx.isPlaying = isplaying
        if(ctx.isPlaying && ctx.isStoping) {
          audioContext.src = `https://music.163.com/song/media/outer/url?id=${ctx.id}.mp3`
          audioContext.title = currentSong.name
          ctx.isStoping = false
        }
        ctx.isPlaying ?  audioContext.play() :  audioContext.pause()

      },

      changeNewMusicAction(ctx, isNext = true) {
        //1. 获取当前的索引
        let index = ctx.playListIndex

        // 2.根据不同的播放模式，获取下一首=歌曲的索引
        switch(ctx.playModeIndex) {
          case 0: //顺序播放
            index = isNext ? index + 1 : index -1
            if(index === -1) index = ctx.palyListSongs.length - 1
            if(index === ctx.palyListSongs.length) index = 0
            break
          case 1: //单曲循坏
            break
          case 2: //随机播放
            index = Math.floor(Math.random() * ctx.playListIndex.length)
            break
        }
     
         // 3.获取歌曲
        let currentSong = ctx.palyListSongs[index]
        if (!currentSong){
          currentSong = ctx.currentSong
        }else {
          ctx.playListIndex = index
        } 

        // 4.播放的歌曲
        this.dispatch("playMusicWithSongIdAction", { id: currentSong.id, isRefresh: true })
      }
    }
 })


export {
 audioContext,
 playerStore
}